package com.xiaozhen.system.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaozhen.common.core.constant.Constants;
import com.xiaozhen.common.core.constant.UserConstants;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.system.SysUser;
import com.xiaozhen.common.core.utils.FileUploadUtils;
import com.xiaozhen.common.core.utils.SecurityUtils;
import com.xiaozhen.common.core.utils.StringUtils;
import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@Api(tags = "系统用户个人信息接口")
@RestController
@RequestMapping("/sysUser/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private FileUploadUtils fileUploadUtils;
    @Value("${remoteServer.imageUrl}")
    private String imageUrl;

    /**
     * 个人信息
     */
    @ApiOperation("个人信息")
    @GetMapping
    public AjaxResult profile() {
        SysUser user = userService.selectUserById(getCurrentUserId());
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(getCurrentUserId()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && !userService.checkPhoneUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && !userService.checkEmailUnique(user)) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        SysUser sysUser = userService.selectUserById(StpUtil.getLoginIdAsLong());
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUser(user) > 0) {
            return AjaxResult.success("修改个人信息成功");
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        SysUser user = userService.selectUserById(StpUtil.getLoginIdAsLong());
        String password = user.getPassword();
        if (!SecurityUtils.matches(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matches(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(getCurrentUserId(), SecurityUtils.encryptPassword(newPassword)) > 0) {
            return AjaxResult.success("修改密码成功");
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            AjaxResult fileResult = fileUploadUtils.uploadFile(file);
            if (StringUtils.isNull(fileResult) || ((int) fileResult.get(AjaxResult.CODE_TAG)) != Constants.SUCCESS) {
                return AjaxResult.error("文件服务异常，请联系管理员");
            }
            String url = imageUrl + fileResult.get(AjaxResult.DATA_TAG);
            if (userService.updateUserAvatar(getCurrentUserId(), url) > 0) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", url);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
